package com.treegrid;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.util.NumUtil;

public class TreegridAction extends ActionSupport {
	private static final long serialVersionUID = 8879350960853362753L;
	
	private Map<String, Object> map;
	private Object data;
	private Map<String, Object> result = new HashMap<String, Object>();
	
	public Object getData() {
		return data;
	}
	
	public void setData(Object data) {
		this.data = data;
	}

	public Map<String, Object> getResult() {
		return result;
	}

	public void setResult(Map<String, Object> result) {
		this.result = result;
	}

	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}

	private Map<String, Object> getFormItem() {
		Map<String, Object> item = new HashMap<String, Object>();
		
		Enumeration<String> params = ServletActionContext.getRequest().getParameterNames();
		while (params.hasMoreElements()) {
			String key = params.nextElement();
			String value = ServletActionContext.getRequest().getParameter(key);
			System.out.println(key + " - " + value);
			item.put(key, value);
		}
		
		return item;
	}
	
	// Form data: id, page, rows
	public String getItems() {
		Map<String, Object> item = getFormItem();
		int id = NumUtil.parseInt((String)item.get("id"), 0);
		int page = NumUtil.parseInt((String)item.get("page"), 1);
		int rows = NumUtil.parseInt((String)item.get("rows"), 10);
		
		if (id == 0) {
			// return map
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", TreegridDataRepo.getRows());
			map.put("rows", TreegridDataRepo.getItems("0", page, rows));
			data = map;
		} else {
			// return list
			data = TreegridDataRepo.getItemByPid("" + id);
		}
		
		return SUCCESS;
	}

	public String saveItem() {
		Map<String, Object> item = getFormItem();
		
		Item flag = TreegridDataRepo.addItem(item);
		if (flag != null) {
			result.put("success", true);
			result.put("data", flag);
		} else {
			result.put("errorMsg", "The Name(" + item.get("name") +") has existed!");
		}
		return SUCCESS;
	}
	
	public String updateItem() {
		Map<String, Object> item = getFormItem();
		Item flag = TreegridDataRepo.updateItem(item);
		if (flag != null) {
			result.put("success", true);
			result.put("data", flag);
		} else {
			result.put("errorMsg", "Update item (" + item.get("name") +") error!");
		}
		return SUCCESS;
	}
	
	public String destroyItem() {
		Map<String, Object> item = getFormItem();
		String id = (String) item.get("id");
		boolean flag = TreegridDataRepo.removeItem(id);
		if (flag) {
			result.put("success", true);
		} else {
			result.put("errorMsg", "Remove item (" + id +") error!");
		}
		return SUCCESS;
	}
}
